package com.usc.blog.web.controller;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
public class UploadFileController {
	@RequestMapping("fileUpload")
	public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws IOException {
		// 用来检测程序运行时间
		long startTime = System.currentTimeMillis();
		System.out.println("fileName：" + file.getOriginalFilename());
		long filetime = 0;
		try {
			// 获取输出流 dataurl

			filetime = new Date().getTime();
			OutputStream os = new FileOutputStream(
					"G:\\apache-tomcat-7.0.93\\webapps\\blogfile\\" + filetime + file.getOriginalFilename());
			// 获取输入流 CommonsMultipartFile 中可以直接得到文件的流
			InputStream is = file.getInputStream();
			int temp;
			// 一个一个字节的读取并写入
			while ((temp = is.read()) != (-1)) {
				os.write(temp);
			}
			os.flush();
			os.close();
			is.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		long endTime = System.currentTimeMillis();
		// System.out.println("方法一的运行时间：" + String.valueOf(endTime - startTime)
		// + "ms");
		// 上传成功之后将进行回显，说文件上传成功；
		request.setAttribute("fileout", "文件上传成功！");
		session.setAttribute("dataurl", "http://localhost:8080/blogfile/" + filetime + file.getOriginalFilename());
		System.out.println("http://localhost:8080/blogfile/" + filetime + file.getOriginalFilename());
		return "user/addblog";
	}
}